import {
  Toast, ImagePreview
} from 'vant';
import { router } from '@/router/permission';

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * 手机号校验
 * @param str
 * @returns {boolean}
 */
export const checkPhone = function(val) {
	const reg = /^1[23456789]\d{9}$/;
	if(!reg.test(val)){
		return false
	} else {
		return true
	}
}

// 轮播图点击
export const bannerToParams = (item) => {
  // console.log(item.jump_type);
  if(item.jump_type === 1) {
    //图片预览
    ImagePreview([item.jump_content]);
  }else if(item.jump_type === 2) {
    // 网页地址
    window.location.href = item.jump_content;
  }else if(item.jump_type === 4) {
    if(item.jump_content=='goods_list_type'){
      if(item.jump_params=='2'){
        // 无忧私域
        router.push({
          name: 'selection',
        })
        // return
      }else if(item.jump_params=='3'){
        // 收银设备
        router.push({
          path: '/new-area?type=device',
        })
      }

  }else if(item.jump_content=='goods_detail'){
    router.push({
      path: '/good?id='+item.jump_params
    })
  }
}else if(item.jump_type === 5){
  // console.log(33);
  localStorage.setItem('content',item.jump_content)
  router.push({
    path: '/content?title='+item.name,
  })
}
}

export const formatSubsidy=(value)=> {
  const subsidy = Number(value) || 0;
  const formattedSubsidy = subsidy.toString().includes('.')
    ? subsidy.toString().split('.')[1].length > 2
      ? subsidy.toString().split('.')[0] + '.' + subsidy.toString().split('.')[1].slice(0, 2)
      : subsidy.toString()
    : subsidy.toString() + '.00';

  return formattedSubsidy;
}